<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\WxPlate;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class WxPlateController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxPlate(), function (Grid $grid) {
            global $__MINI_GLOBAL_TENANT_ID__;
            $grid->model()->where('tenant_id', '=', $__MINI_GLOBAL_TENANT_ID__);
            $grid->quickSearch(['id', 'plate_name','plate_introduce'])->placeholder('搜索id，名称，描述...')->width(50);
//            $grid->column('id')->sortable();
            $grid->column('plate_name')->editable();
            $grid->column('sort')->editable();
            $grid->column('plate_introduce');
            $grid->column('plate_state')->switch();
//            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();
            $grid->model()->orderBy('id', 'desc');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('plate_name');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxPlate(), function (Show $show) {
            $show->field('id');
            $show->field('plate_name');
            $show->field('plate_introduce');
            $show->field('plate_state');
            $show->field('tenant_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxPlate(), function (Form $form) {


            $form->display('id');
            $form->text('plate_name');
            $form->number('sort');
            $form->text('plate_introduce');
            $form->switch('plate_state');

            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $form->text('tenant_id', '本站分应用id')->help('忽略这个配置')->default($__MINI_GLOBAL_TENANT_ID__);
            }

            $form->saving(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                $form->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
            });

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    if(\App\Models\WxPlate::where('id', $form->getKey())->value('tenant_id') != $__MINI_GLOBAL_TENANT_ID__){
                        return $form->response()->error('权限不足，不可以删除其他分站对象');
                    }
                }
            });

        });
    }
}
